import React, { useRef, useEffect } from 'react';
import { init, getInstanceByDom } from 'echarts';
import type { CSSProperties } from 'react';
import type { ECharts, SetOptionOpts } from 'echarts';

export interface ReactEChartsProps {
    option: any;
    style?: CSSProperties;
    settings?: SetOptionOpts;
    loading?: boolean;
    theme?: 'light' | 'dark';
}

export function useEcharts(el: React.RefObject<HTMLDivElement>, chartOptions: ReactEChartsProps) {
    const { option, settings, loading, theme } = chartOptions;
    const chartRef = useRef<ECharts | null>(null);

    useEffect(() => {
        // 初始化图表
        if (el.current) {
            chartRef.current = init(el.current, theme);
        }

        // 添加图表大小变化监听
        const resizeObserver = new ResizeObserver(() => {
            chartRef.current?.resize();
        });

        if (el.current) {
            resizeObserver.observe(el.current);
        }

        // 清理函数
        return () => {
            chartRef.current?.dispose();
            if (el.current) {
                resizeObserver.unobserve(el.current);
            }
        };
    }, [theme]);

    useEffect(() => {
        // 更新图表配置
        if (el.current) {
            const chart = getInstanceByDom(el.current);
            chart?.setOption({ ...option, ...settings, backgroundColor: 'transparent' });
        }
    }, [option, settings, theme]);

    useEffect(() => {
        chartRef.current?.resize();
        // 根据 loading 状态显示/隐藏加载动画
        if (el.current) {
            const chart = getInstanceByDom(el.current);
            loading === true ? chart?.showLoading() : chart?.hideLoading();
        }
    }, [loading, theme]);

    return el;
}
